package aor2.components;

import aor2.common.Tracker;
import aor2.components.records.RecordFF;
import aor2.cpu.ClockCPU;

public abstract class FlipFlop implements ElementIO {

	private Tracker history;

	protected FlipFlop(boolean state) {
		super();
		this.state = state;
		history = new Tracker();
		history.put(new RecordFF(this));
	}

	protected boolean state;

	public boolean state() {
		return state;
	}

	protected void setState(boolean state) {
		if (this.state != state) {
			this.state = state;
			history.put(new RecordFF(this));
		}
		this.state = state;
	}

	@Override
	abstract public void in() throws FlipFlopException;

	@Override
	abstract public void out() throws FlipFlopException;

	public Tracker getHistory() {
		return history;
	}

	public void previousClk() {
		RecordFF tmp = (RecordFF) history.getFromTop(0);
		if (tmp != null) {
			while (((ClockCPU) (tmp).getMark()).compareTo(ClockCPU
					.getInstance()) > 0 && tmp != null) {
				history.takeFromTop();
				tmp = (RecordFF) history.getFromTop(0);
			}
			if (tmp != null)
				//setState(((RecordFF) history.takeFromTop()).getValue());
				state = tmp.getValue();
		}
	}

}
